import React, { useEffect, useState } from 'react';
import {
  Input,
  Select,
  Button,
  Table,
  Pagination,
  Space,
} from 'antd';
import axios from 'axios';
import {
  SearchOutlined,
} from '@ant-design/icons';

const { Option } = Select;

// API基础URL，复用与入库页面一致的后端地址
const API_BASE_URL = 'http://localhost:3000';

// 出库记录行类型
interface OutboundRow {
  key: string | number;
  serialNumber: string;
  outboundNumber: string;
  itemName: string;
  plannedQuantity: number;
  actualQuantity: number;
  unit: string;
  warehouse: string;
  storageArea: string;
  storageLocation: string;
  creator: string;
}

// 后端返回的出库记录字段
interface OutboundItem {
  key?: string | number;
  id: number;
  sort?: string;
  code?: number | string;
  name?: string;
  cate?: string;
  actualnum?: number | string;
  fieldName?: string;
  warehouse?: string;
  reservoir?: string;
  location?: string;
  add?: string;
  addtime?: string;
  edit?: string;
  edittime?: string;
  tracking?: string;
  plannum?: number | string;
}

// 表格列配置
const columns = [
  {
    title: '',
    dataIndex: 'check',
    render: () => <Input type="checkbox" style={{ marginLeft: 8 }} />,
  },
  {
    title: '序号',
    dataIndex: 'serialNumber',
    render: (text) => <span style={{ color: 'blue' }}>{text}</span>,
  },
  {
    title: '出库单号',
    dataIndex: 'outboundNumber',
  },
  {
    title: '物品名称',
    dataIndex: 'itemName',
  },
  {
    title: '计划数量',
    dataIndex: 'plannedQuantity',
  },
  {
    title: '实际数量',
    dataIndex: 'actualQuantity',
  },
  {
    title: '单位',
    dataIndex: 'unit',
  },
  {
    title: '仓库',
    dataIndex: 'warehouse',
  },
  {
    title: '库区',
    dataIndex: 'storageArea',
    render: (text) => <span style={{ color: 'blue' }}>{text}</span>,
  },
  {
    title: '库位',
    dataIndex: 'storageLocation',
  },
  {
    title: '创建人',
    dataIndex: 'creator',
    render: (text) => <span style={{ color: 'blue' }}>{text}</span>,
  },
];

const Ckjilu = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<OutboundRow[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 拉取出库记录
  const fetchOutbound = async () => {
    setLoading(true);
    try {
      const res = await axios.get(`${API_BASE_URL}/api/outbound`);
      const list: OutboundItem[] = Array.isArray(res.data) ? res.data : [];
      // 映射为表格字段
      const mapped: OutboundRow[] = list.map((item: OutboundItem, idx: number) => ({
        key: item.key ?? idx,
        serialNumber: String(item.sort ?? ''),
        outboundNumber: String(item.tracking ?? ''),
        itemName: String(item.name ?? ''),
        plannedQuantity: Number(item.plannum ?? 0),
        actualQuantity: Number(item.actualnum ?? 0),
        unit: String(item.fieldName ?? ''),
        warehouse: String(item.warehouse ?? ''),
        storageArea: String(item.reservoir ?? ''),
        storageLocation: String(item.location ?? ''),
        creator: String(item.add ?? ''),
      }));
      setDataSource(mapped);
    } catch (err) {
      console.error('获取出库记录失败:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOutbound();
  }, []);
  // 搜索处理函数
  const handleSearch = () => {
    console.log('执行搜索操作');
    // 这里可添加实际搜索逻辑，如根据表单值过滤表格数据等
  };

  // 重置处理函数
  const handleReset = () => {
    console.log('执行重置操作');
    // 这里可添加重置表单逻辑
  };

  return (
    <div style={{ padding: '20px' }}>
      {/* 搜索区域 */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          marginBottom: '20px',
          justifyContent: 'flex-start',
        }}
      >
        <Space>
          <Input
            placeholder="请输出库单号"
            prefix={<SearchOutlined />}
            style={{ width: 150 }}
          />
          <Input
            placeholder="物品名称"
            prefix={<SearchOutlined />}
            style={{ width: 150 }}
          />
          <span>出库时间</span>
          <Select placeholder="起始日期—结束日期" style={{ width: 150 }}>
            <Option value="range">起始日期—结束日期</Option>
            {/* 可根据需要添加其他选项 */}
          </Select>
        </Space>
        <Space style={{ marginLeft: '20px' }}>
          <Button type="primary" onClick={handleSearch}>搜索</Button>
          <Button onClick={handleReset}>重置</Button>
        </Space>
      </div>

      {/* 表格区域 */}
      <Table
        dataSource={dataSource.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
        columns={columns}
        loading={loading}
        pagination={false} // 关闭表格自带分页，使用下方自定义分页
        scroll={{ x: 'scroll' }} // 横向滚动
        rowClassName={(record, index) => (index % 2 === 0 ? 'even-row' : 'odd-row')} // 行交替样式
      />

      {/* 分页区域 */}
      <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Pagination
          current={currentPage}
          total={Array.isArray(dataSource) ? dataSource.length : 0}
          pageSize={pageSize}
          onChange={(page, size) => {
            setCurrentPage(page);
            setPageSize(size || 10);
          }}
          showSizeChanger
          showQuickJumper
        />
        <Space>
          <span>{pageSize}条/页</span>
          <span>跳至</span>
          <Input 
            type="text" 
            style={{ width: 50, textAlign: 'center' }} 
            onPressEnter={(e) => {
              const value = (e.target as HTMLInputElement).value;
              const page = parseInt(value, 10);
              const totalPages = Math.ceil((Array.isArray(dataSource) ? dataSource.length : 0) / pageSize);
              if (!Number.isNaN(page) && page > 0 && page <= totalPages) {
                setCurrentPage(page);
              }
            }}
          />
          <span>页</span>
        </Space>
      </div>
    </div>
  );
};

// 行交替样式（在 CSS 文件中）
// .even-row {
//   background-color: #fafafa;
// }
// .odd-row {
//   background-color: #fff;
// }

export default Ckjilu;